package com.employee.service.impl;

import com.employee.exception.PasswordErrorException;
import com.employee.exception.UserNotExistException;
import com.employee.mapper.UserMapper;
import com.employee.pojo.dto.PwdDTO;
import com.employee.pojo.dto.UserDTO;
import com.employee.pojo.entry.User;
import com.employee.pojo.vo.UserInfoVO;
import com.employee.service.UserService;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    // 登录
    @Override
    public User login(UserDTO userDTO) {
        // 1. 查询用户是否存在
        User user = userMapper.selectByEmail(userDTO);
        System.out.println("user = " + user);
        if (user == null) {
            throw new UserNotExistException("用户不存在");
        }
        // System.out.println(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
        // System.out.println(BCrypt.hashpw("123456@", BCrypt.gensalt()));
        if (BCrypt.checkpw(userDTO.getPassword(), user.getPassword())) {
            return user;
        } else  {
            throw new PasswordErrorException("密码错误");
        }
    }

    // 获取用户信息
    @Override
    public UserInfoVO getUserInfo(Long id) {
        UserInfoVO userInfo = userMapper.getUserInfo(id);
        // 处理日期
        System.out.println("userInfo = " + userInfo);
        return userInfo;
    }

    // 修改密码
    @Override
    public void updatePwd(PwdDTO pwdDTO) {
        System.out.println("pwdDTO = " + pwdDTO);
        User user = userMapper.selectByEmail(new UserDTO(pwdDTO.getEmail(), null));
        if (user == null) {
            throw new UserNotExistException("邮箱不存在");
        }
        System.out.println(pwdDTO.getOldPassword());
        System.out.println(BCrypt.checkpw("mepbw*&!W1I*", user.getPassword()));
        if (BCrypt.checkpw(pwdDTO.getOldPassword(), user.getPassword())) {
            user.setEmail(null);
            user.setPassword(BCrypt.hashpw(pwdDTO.getNewPassword(), BCrypt.gensalt()));
            user.setUpdateTime(LocalDateTime.now());
            userMapper.update(user);
        } else {
            throw new PasswordErrorException("旧密码错误");
        }
    }
}
